package com.micro.edu.service;

import com.micro.edu.dao.MicroAuthCodeDao;
import com.micro.edu.feign.EmailServiceFeignClient;
import com.micro.edu.pojo.MicroAuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;
import java.util.Random;

/**
 * @author Tyd
 * @date 2021/03/08 16:12
 */
@Service
public class CodeService {

    @Value("${code.expireTime:10}")
    private final Integer expireTime = 10;

    @Autowired
    private MicroAuthCodeDao microAuthCodeDao;
    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;

    public boolean create(String email) {
        MicroAuthCode microAuthCode = new MicroAuthCode();
        microAuthCode.setEmail(email);
        Example<MicroAuthCode> example = Example.of(microAuthCode);
        Optional<MicroAuthCode> optional = microAuthCodeDao.findOne(example);
        LocalDateTime now = LocalDateTime.now();
        if (optional.isPresent()) {
            microAuthCode = optional.get();
            LocalDateTime expiretime = microAuthCode.getExpiretime();
            if (expiretime.isAfter(now)) {
                return false;
            }
        }
        String code = getCode();
        microAuthCode.setCode(code);
        microAuthCode.setCreatetime(now);
        microAuthCode.setExpiretime(now.plusMinutes(expireTime));
        microAuthCodeDao.save(microAuthCode);
        emailServiceFeignClient.send(email,code);
        return true;
    }

    private String getCode() {
        Random random = new Random();
        int code = random.nextInt(1_000_000);
        return String.format("%6d", code);
    }

    public int validate(String email, String code) {
        MicroAuthCode microAuthCode = new MicroAuthCode();
        microAuthCode.setEmail(email);
        microAuthCode.setCode(code);
        Optional<MicroAuthCode> optional = microAuthCodeDao.findOne(Example.of(microAuthCode));
        if (optional.isEmpty()) {
            return 1;
        }
        return 0;
    }
}
